import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/dio.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/material.dart';
import 'logger.dart';

class HttpClient {
  // static const String baseUrl = 'https://trying.jinhubianli.com/app/';
  static const String baseUrl = 'http://47.93.6.88:8810';
  static Dio? _dio;
  static Dio? _externalDio;
  static GlobalKey<ScaffoldMessengerState>? _scaffoldKey;
  static CookieJar? _cookieJar;


  static void init(GlobalKey<ScaffoldMessengerState> scaffoldKey) {
    _scaffoldKey = scaffoldKey;
    _cookieJar = CookieJar();
  }

  static Dio get dio {
    _dio ??= Dio(BaseOptions(
      baseUrl: baseUrl,
      connectTimeout: const Duration(seconds: 30),
      receiveTimeout: const Duration(seconds: 30),
      sendTimeout: const Duration(seconds: 30),
      validateStatus: (status) => true,
    ))..interceptors.add(CookieManager(_cookieJar!))..interceptors.add(
        LogInterceptor(
          requestBody: true,
          requestHeader: true,
          responseBody: true,
          error: true,
        )
    );
    return _dio!;
  }

  static Dio get externalDio {
    _externalDio ??= Dio(BaseOptions(
      connectTimeout: const Duration(seconds: 30),
      receiveTimeout: const Duration(seconds: 30),
      sendTimeout: const Duration(seconds: 30),
      validateStatus: (status) => true,
    ))..interceptors.add(
      InterceptorsWrapper(
        onRequest: (options, handler) {
          Logger.i('Request: ${options.queryParameters} ${options.path}');
          return handler.next(options);
        },
        onResponse: (response, handler) {
          Logger.i('Response: ${response.statusCode} ${response.requestOptions.path}');
          final cookies = response.headers['set-cookie'];
          if (cookies != null && cookies.isNotEmpty) {
            Logger.d('Received cookies: $cookies');
          }
          return handler.next(response);
        },
        onError: (DioException e, handler) {
          return handler.next(e);
        },
      )
    );
    return _externalDio!;
  }

  static Future<void> initInterceptors() async {

    dio.interceptors.add(InterceptorsWrapper(
      onRequest: (options, handler) {
        Logger.i('Request: ${options.data} ${options.path}');
        return handler.next(options);
      },
      onResponse: (response, handler) {
        Logger.i('Response: ${response.statusCode} ${response.requestOptions.path}');
        // if (response.statusCode == 500) {
        //   String errorMessage = '服务器内部错误';
        //   try {
        //     if (response.data is Map && response.data['message'] != null) {
        //       errorMessage = response.data['message'];
        //     } else if (response.data is String) {
        //       errorMessage = response.data;
        //     }
        //   } catch (e) {
        //     Logger.e('Error parsing error message', e);
        //   }
        //
        //   _scaffoldKey?.currentState?.showSnackBar(
        //     SnackBar(content: Text(errorMessage)),
        //   );
        //
        //   final error = DioException(
        //     requestOptions: response.requestOptions,
        //     response: response,
        //     type: DioExceptionType.badResponse,
        //   );
        //   return handler.reject(error);
        // }
        final cookies = response.headers['set-cookie'];
        if (cookies != null && cookies.isNotEmpty) {
          Logger.d('Received cookies: $cookies');
        }
        return handler.next(response);
      },
      onError: (DioException e, handler) {
        return handler.next(e);
      },
    ));
  }
} 